//
//  DownloadTableViewCell.m
//  DCDownloadOpration
//
//  Created by Wade on 16/4/4.
//  Copyright © 2016年 Wade. All rights reserved.
//

#import "DownloadTableViewCell.h"
#import "DCDownload.h"
#import "DCProgressView.h"

@interface  DownloadTableViewCell()
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;

@property (weak, nonatomic) IBOutlet UIButton *downloadBtn;
@property (weak, nonatomic) IBOutlet DCProgressView *progressView;
@end

@implementation DownloadTableViewCell
+ (instancetype)cellWithTableView:(UITableView *)tableView
{
    DownloadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"DownloadTableViewCell" owner:nil options:nil] lastObject];
    }

    return cell;
}
- (void)setUrlStr:(NSString *)urlStr
{
    _urlStr =  urlStr;
    self.titleLabel.text = [self.urlStr lastPathComponent];
}

- (IBAction)downloadBtnClick:(id)sender {
    NSString *cachePath = [DCCachesPath stringByAppendingPathComponent:[self.urlStr lastPathComponent]];
    self.downloadBtn.hidden = YES;
    self.progressView.hidden = NO;
    [self.manager download:self.urlStr toDestinationPath:cachePath progress:^(NSInteger curentBytes, NSInteger TotalBytes, DCDownloadOpration *downloadopration) {
        self.progressView.progress = (double)curentBytes / (double)TotalBytes;
        
    } state:^(DCDownloadState state, NSString *file, NSError *error, DCDownloadOpration *downloadopration) {
        self.state = state;
        if (state==DCDownloadStateCompleted || state == DCDownloadStateFail) {
        
            dispatch_async(dispatch_get_main_queue(), ^{
                self.downloadBtn.hidden = NO;
                self.progressView.hidden = YES;
                  [self.downloadBtn setImage:[UIImage imageNamed:@"check"] forState:UIControlStateNormal];
            });
          
        }
    }];
}

@end
